package leeon.mobile.server.bbscache;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于缓存图片的servlet
 * 对于请求的图片，先查看数据库是否有，
 * 如果有提取返回，返回一个默认的图片，放入到queue中，等待执行提取任务进行提取
 * @author leeon
 */
@SuppressWarnings("serial")
public class BbsuploadServlet extends HttpServlet {
		
	public static final byte[] DEFAULT = new byte[16];
	
	private BBSUploadService service = new BBSUploadService();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String pathInfo = req.getPathInfo();
		boolean fromQueue = "true".equals(req.getParameter("fromQueue"));
		int size = 0;
		try {
			String s = req.getParameter("size");
			size = (s!=null&&s.length()!=0)?Integer.parseInt(s):0;
		} catch (Exception e) {
			size = 0;
		}
		
		//首先查看一次是否有该图
		byte[] blob = service.getPicture(pathInfo);
		//没有的话，有两种情况，
		//当前在深夜，不做提取，只是加入队列
		//当前不在深夜，立刻提取并且保存
		if (blob == null) {
			//no this path, add queue and fetch
			if (Utils.isNight()) {//add queue
				QueueService.addPicQueueDelay(pathInfo);
			} else {
				//提取并且保存
				blob = service.savePicture(pathInfo);
			}	
		}
		
		//如果是来自非内部的请求，那么输出，否则不输出
		if (!fromQueue) {
			if (blob == null || blob.length == 0) {
				//has path but over 1M, give a default pic
				blob = DEFAULT;
			} else if (size != 0) {
				blob = service.resize(blob, size);
			}
			resp.setBufferSize(1024);
			OutputStream os = resp.getOutputStream();
			try {
				os.write(blob);
			} finally {
				os.flush();
				os.close();
			}
		}
	}
	
	//非主版，将会使用post方法调用该servlet，
	//该servlet发起一个到主板的get请求
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String pathInfo = req.getPathInfo();
		boolean fromQueue = "true".equals(req.getParameter("fromQueue"));
		
		if (fromQueue) {
			String url = BBSUploadService.PIC_URL_INNER + pathInfo + "?fromQueue=true";
			InputStream is = Utils.readUrl(url);
			try {
			} finally {
				is.close();
			}
		}
	}
}
